package com.zhongxi.guoyuan.view.personalCenter;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.OffLineShop.Adapter.OfflineHasConsumeAdapter;
import com.zhongxi.guoyuan.OffLineShop.Model.OffLineHasConsumeResult;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.ClearWeedConsumeAdapter;
import com.zhongxi.guoyuan.adapter.FacePayOrderAdapter;
import com.zhongxi.guoyuan.adapter.personCenter.ClearWeedExchangeAdapter;
import com.zhongxi.guoyuan.adapter.personCenter.InnerOrderAdapter;
import com.zhongxi.guoyuan.adapter.rewardCoin.RewardAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.center.InnerOrderResult;
import com.zhongxi.guoyuan.entity.clearweed.ClearConsumeResult;
import com.zhongxi.guoyuan.entity.facetoface.FacePayDataResult;
import com.zhongxi.guoyuan.entity.facetoface.FaceShopInfo;
import com.zhongxi.guoyuan.entity.rewardcoin.RewardCoinOrderInfo;
import com.zhongxi.guoyuan.entity.rewardcoin.RewardCoinOrderResult;
import com.zhongxi.guoyuan.entity.seller.OrderInfos;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.view.beautifulStore.ProjectDetailActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HasConsumeActivity extends BaseActivity implements View.OnClickListener, PullToRefreshBase.OnRefreshListener2<ListView>, AdapterView.OnItemClickListener {

    private TextView tvTitle;
    private ImageView ivBack;
    private TextView tvCoin;
    private TextView tvReward;
    private TextView tvBeautiful;
    private TextView tvOffReward;
    private TextView tvBean;

    private Map<String, String> map = new HashMap<>();
    private PullToRefreshListView lvList;
    private String type;
    private String flag = "1";
    private InnerOrderAdapter innerAdapter;
    private List<InnerOrderResult.InnerOrderData> data = new ArrayList<>();
    private List<RewardCoinOrderInfo> rewardData = new ArrayList<>();
    private List<FacePayDataResult.FaceOrderInfo> faceData = new ArrayList<>();
    private List<ClearConsumeResult.DataBean> dataBeans=new ArrayList<>();
    private List<OrderInfos> postCoinData = new ArrayList<>();
    private List<OffLineHasConsumeResult.OrderInfoBean> offLineData=new ArrayList<>();
    private FacePayOrderAdapter coinAdapter;
    private JSONObject mirrorInfoObject;
    private RewardAdapter rewardAdapter;
    private ListView refreshableView;
    private int objPosition;
    private FaceShopInfo faceShopInfo;
    private FacePayOrderAdapter facePayAdapter;
    private ClearWeedConsumeAdapter exchangeAdapter;
    private OfflineHasConsumeAdapter offlineAdapter;
    private int index;


    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_has_consume);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvBeautiful = (TextView) findViewById(R.id.tvBeautiful);
        tvReward = (TextView) findViewById(R.id.tvReward);
        tvCoin = (TextView) findViewById(R.id.tvCoin);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        tvOffReward= (TextView) findViewById(R.id.tvOffReward);
        tvBean= (TextView) findViewById(R.id.tvBean);

        lvList = (PullToRefreshListView) findViewById(R.id.lvList);
        lvList.setMode(PullToRefreshBase.Mode.BOTH);
        refreshableView = lvList.getRefreshableView();
        tvTitle.setText("消费记录");
        index = getIntent().getIntExtra("index", 0);

        initSelect();


    }

    private void initSelect() {
        switch (index){
            case 0:
                tvBeautiful.setSelected(true);
                flag="1";
                getInner();
                break;
            case 1:
                tvReward.setSelected(true);
                flag="2";
                getReward();
                break;
            case 2:
                tvCoin.setSelected(true);
                flag="3";

                getFacePay();
                break;
            case 3:
                tvOffReward.setSelected(true);
                flag="5";

                getOffReward();
                break;
            case 4:
                tvBean.setSelected(true);
                flag="4";

                getClearWeed();
                break;
        }

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //删除订单记录
                    objPosition = (int) msg.obj;
                    deleteOrder(objPosition);
                    break;
                case 1:

                    break;
            }
        }
    };

    @Override
    protected void initData() {
        super.initData();
//        getInner();

    }


    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("inner".equals(type)) {
                InnerOrderResult result = gson.fromJson(response, InnerOrderResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (pageNum == 1) {
                    data.clear();
                    lvList.setAdapter(null);
                }
                if (null != result.getDate() && result.getDate().size() > 0) {
                    data.addAll(result.getDate());
                } else {

                    lvList.onRefreshComplete();
                    return;
                }
                lvList.onRefreshComplete();
                innerAdapter = new InnerOrderAdapter(context, data, handler);
                lvList.setAdapter(innerAdapter);
            } else if ("reward".equals(type)) {
                RewardCoinOrderResult result = gson.fromJson(response, RewardCoinOrderResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                if (pageNum == 1) {
                    rewardData.clear();
                    lvList.setAdapter(null);
                }
                if (result.getOrderInfo() != null && result.getOrderInfo().size() > 0) {
                    List<RewardCoinOrderInfo> orderInfo = result.getOrderInfo();
                    rewardData.addAll(orderInfo);
                } else {
                    lvList.onRefreshComplete();
                    return;
                }
                JSONObject obj = new JSONObject(response);
                JSONObject mirrorInfo = obj.optJSONObject("orderMirror");
                JSONObject shopInfo = obj.optJSONObject("shopInfo");
                JSONObject orderCus = obj.optJSONObject("orderCus");
                rewardAdapter = new RewardAdapter(context, rewardData, mirrorInfo, handler,orderCus);
                lvList.setAdapter(rewardAdapter);
                rewardAdapter.setShopInfo(shopInfo);
                rewardAdapter.notifyDataSetChanged();
                lvList.onRefreshComplete();
            } else if ("face".equals(type)) {

                FacePayDataResult result = gson.fromJson(response, FacePayDataResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }

                if (pageNum == 1) {
                    faceData.clear();
                    lvList.setAdapter(null);
                }
                if (result.getOrderInfo() != null && result.getOrderInfo().size() > 0) {
                    List<FacePayDataResult.FaceOrderInfo> orderInfo = result.getOrderInfo();
                    faceData.addAll(orderInfo);
                } else {

                    lvList.onRefreshComplete();
                    return;
                }
                faceShopInfo = new FaceShopInfo();

                faceShopInfo = result.getShopInfo();

                facePayAdapter = new FacePayOrderAdapter(context, faceData, faceShopInfo,handler);
                lvList.setAdapter(facePayAdapter);

                facePayAdapter.notifyDataSetChanged();
                lvList.onRefreshComplete();
            } else if ("clearweed".equals(type)) {

                ClearConsumeResult result = gson.fromJson(response, ClearConsumeResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }

                if (pageNum == 1) {
                    dataBeans.clear();
                    lvList.setAdapter(null);
                }
                if (result.getData()!= null && result.getData().size() > 0) {
                    dataBeans.addAll(result.getData());
                } else {
                    lvList.onRefreshComplete();
                    return;
                }
                exchangeAdapter=new ClearWeedConsumeAdapter(context,dataBeans,handler);
                lvList.setAdapter(exchangeAdapter);

                exchangeAdapter.notifyDataSetChanged();
                lvList.onRefreshComplete();
            }else if (type.equals("offreward")){
                OffLineHasConsumeResult result=gson.fromJson(response,OffLineHasConsumeResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (pageNum==1){
                    offLineData.clear();
                    lvList.setAdapter(null);
                }

                if (result.getOrderInfo()!=null&&result.getOrderInfo().size()>0){
                    offLineData.addAll(result.getOrderInfo());
                }else {
                    lvList.onRefreshComplete();
                    return;
                }

                JSONObject jsonObject=new JSONObject(response);
                JSONObject string = jsonObject.optJSONObject("shopInfo");

                offlineAdapter=new OfflineHasConsumeAdapter(this,handler);
                lvList.setAdapter(offlineAdapter);
                offlineAdapter.setList(offLineData,string);

                offlineAdapter.notifyDataSetChanged();
                lvList.onRefreshComplete();
            }else if ("delete".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }

                switch (flag) {
                    case "1":
                        data.remove(objPosition);
                        innerAdapter.notifyDataSetChanged();
                        getInner();
                        break;
                    case "2":
                        rewardData.remove(objPosition);
                        rewardAdapter.notifyDataSetChanged();
                        getReward();
                        break;
                    case "3":
                        faceData.remove(objPosition);
                        facePayAdapter.notifyDataSetChanged();
                        getFacePay();
                        break;
                    case "5":
                        offLineData.remove(objPosition);
                        showShortToast("删除成功");
                        offlineAdapter.notifyDataSetChanged();
                        getOffReward();
                        break;
                    case "4":
                        showShortToast("删除成功");
                        dataBeans.remove(objPosition);
                        exchangeAdapter.notifyDataSetChanged();
                        getClearWeed();
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            lvList.onRefreshComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tvBeautiful.setOnClickListener(this);
        tvReward.setOnClickListener(this);
        tvCoin.setOnClickListener(this);
        tvOffReward.setOnClickListener(this);
        tvBean.setOnClickListener(this);
        lvList.setOnRefreshListener(this);
        lvList.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvBeautiful:
                //美币美容院消费记录
                pageNum = 1;
                flag = "1";
                changeState(tvBeautiful,tvReward,tvCoin,tvOffReward,tvBean);
                getInner();
                break;
            case R.id.tvReward:
                //赚豆超市记录
                pageNum = 1;
                flag = "2";
                changeState(tvReward,tvBeautiful,tvCoin,tvOffReward,tvBean);
                getReward();
                break;
            case R.id.tvCoin: //当面付
                pageNum = 1;
                flag = "3";
                changeState(tvCoin,tvBeautiful,tvReward,tvOffReward,tvBean);

                getFacePay();
                break;
            case R.id.tvOffReward:

                pageNum=1;
                flag="5";
                changeState(tvOffReward,tvBeautiful,tvReward,tvCoin,tvBean);

                getOffReward();
                break;
            case R.id.tvBean:
                pageNum=1;
                flag="4";
                changeState(tvBean,tvBeautiful,tvReward,tvCoin,tvOffReward);
                getClearWeed();
                break;


        }
    }
    private void changeState(View view1,View view2,View view3,View view4,View view5){
        view1.setSelected(true);
        view2.setSelected(false);
        view3.setSelected(false);
        view4.setSelected(false);
        view5.setSelected(false);
    }

    /**
     * 获取美容院订单
     */
    private void getInner() {
        type = "inner";
        getServer(Url.INNER_ORDER, null, "&page=" + pageNum, false, null, "get");
    }

    /**
     * 赚豆超市订单
     */
    private void getReward() {
        type = "reward";
        getServer(Url.REWARD_TO_ORDER, null, "&page=" + pageNum, false, null, "get");
    }

    /**
     * 当面付订单
     */
    private void getFacePay() {
        type = "face";
        getServer(Url.FACE_PAY_ORDER, null, "&page=" + pageNum, false, null, "get");
    }
    /**
     * 美豆兑换订单
     */
    private void getClearWeed() {
        type = "clearweed";
        getServer(Url.CLEARWEED_RECORD, null, "&page=" + pageNum, false, null, "get");
    }
    /***
     *线下商家消费记录
     */
    private void getOffReward(){
        type="offreward";
        getServer(Url.OFFLINE_RECODE,null,"&page="+pageNum,false,null,"get");
    }


    /**
     * 删除订单记录
     *
     * @param objPosition
     */
    private void deleteOrder(int objPosition) {
        try {
            type = "delete";
            map.clear();
            switch (flag) {
                case "1":
                    map.put("orderids", data.get(objPosition).getId());
                    break;
                case "2":
                    map.put("orderids", rewardData.get(objPosition).getId());
                    break;
                case "3":
                    map.put("orderids", faceData.get(objPosition).getId());
                    break;
                case "4":
                    map.put("orderids",dataBeans.get(objPosition).getId());
                    break;
                case "5":
                    map.put("orderids",offLineData.get(objPosition).getId());
                    break;
            }
            map.put("ordertype", flag);
            getServer(Url.DELETE_ORDER, map, "", false, null, "post");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        switch (type) {
            case "inner":
                pageNum = 1;
                getInner();
                break;

            case "reward":
                pageNum = 1;
                getReward();
                break;
            case "face":
                pageNum = 1;
                getFacePay();
                break;
            case "clearweed":
                pageNum=1;
                getClearWeed();
                break;
            case "offreward":
                pageNum=1;
                getOffReward();
                break;
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        switch (type) {
            case "inner":
                pageNum++;
                getInner();
                break;

            case "reward":
                pageNum++;
                getReward();
                break;
            case "face":
                pageNum++;
                getFacePay();
                break;
            case "clearweed":
                pageNum++;
               getClearWeed();
                break;
            case "offreward":
                pageNum++;
                getOffReward();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        switch (type) {
            case "inner":
                Intent intent1 = new Intent(context, ProjectDetailActivity.class);
                intent1.putExtra("id", data.get(position - 1).getItemid());
                startActivity(intent1);
                break;
            case "reward":
                if (position - 1 == rewardAdapter.getmExpandedMenuPos()) {
                    rewardAdapter.setmExpandedMenuPos(-1);
                } else {
                    rewardAdapter.setmExpandedMenuPos(position - 1);
                }

                rewardAdapter.notifyDataSetChanged();
                refreshableView.setSelection(position);
                break;
            case "face":
//                if (position - 1 == facePayAdapter.getmExpandedMenuPos()) {
//                    facePayAdapter.setmExpandedMenuPos(-1);
//                } else {
//                    facePayAdapter.setmExpandedMenuPos(position - 1);
//                }
//                facePayAdapter.notifyDataSetChanged();
//                refreshableView.setSelection(position);
                break;
        }
    }
}
